<template>
  <a-modal
    title="修改密码"
    centered
    v-model="visible"
    @ok="handle"
  >
    <a-form :form="form" layout="vertical">
      <a-form-item label="原密码">
        <a-input-password
          v-decorator="[ 'old', {rules: [{ required: true, message: '请输入原密码'}]} ]"
          placeholder="请输入原密码  (初始密码 666666)" />
      </a-form-item>
      <a-form-item label="新密码">
        <a-input-password
          v-decorator="[ 'np', {rules: [{ required: true, message: '请输入新密码'}, {validator: handlePass}]} ]"
          rows="4"
          placeholder="请输入新密码"/>
      </a-form-item>
      <a-form-item label="重复新密码">
        <a-input-password
          v-decorator="[ 're', {rules: [{ required: true, message: '请在次输入新密码'}, {validator: handleConfirmPass}]} ]"
          rows="4"
          placeholder="请在次输入新密码"/>
      </a-form-item>
      <!-- <a-form-item>
        <a-button type="primary" @click="handle">保存</a-button>
        <a-button style="margin-left: 8px" @click="handle">取消</a-button>
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>

<script>
import md5 from 'md5'
import { editPassword } from '@/api/setting'

export default {
  data () {
    return {
      form: this.$form.createForm(this),
      visible: false
    }
  },
  methods: {
    handlePass (rule, value, callback) {
      this.password = value
      callback()
    },
    handleConfirmPass (rule, value, callback) {
      if (this.password && this.password !== value) {
        // eslint-disable-next-line standard/no-callback-literal
        callback('两次密码输入不一致！')
      }
      callback()
    },
    show () {
      this.visible = !this.visible
    },
    handle (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          const old = md5(this.form.getFieldValue('old'))
          const np = md5(this.form.getFieldValue('np'))
          editPassword(this.$store.getters.userInfo.id, old, np).then(res => {
            this.show()
          })
        }
      })
    }
  }
}
</script>
